package com.gugee.ins.data.analysis.service.impl;

import com.gugee.common.thread.ScheduleTemplate;
import com.gugee.ins.common.dal.service.brand.InsBrandDao;
import com.gugee.ins.data.analysis.config.InsAnalysisConfig;
import com.gugee.ins.data.analysis.service.InsAnalysisBrandCategoryService;
import com.gugee.ins.data.common.msg.InsBrandMessage;
import com.xiguaji.boot.toolkit.ThreadPoolUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.ForkJoinPool;

/**
 * InsAnalysisBrandService 服务
 * @author Huangxin
 */
@Slf4j
@Service
public class InsAnalysisBrandCategoryServiceImpl implements InsAnalysisBrandCategoryService {

    /**
     * 配置
     */
    @Autowired
    InsAnalysisConfig insAnalysisConfig;

    /**
     * 线程调度
     */
    @Autowired
    ScheduleTemplate scheduleTemplate;

    /**
     * insBrandDao
     */
    @Autowired
    InsBrandDao insBrandDao;

    /**
     * 线程池
     */
    ForkJoinPool forkJoinPool;

    /**
     * 线程名
     */
    private String workName = "insAnalysisBrandCategory-worker";

    /**
     * 初始化线程池
     */
    @PostConstruct
    public void init() {
        forkJoinPool = ThreadPoolUtils.forkJoinPool(insAnalysisConfig.getInsAnalysisBrandCategoryCorePollSize(), workName);
        scheduleTemplate.attach(workName, forkJoinPool);
    }

    /**
     * 处理 分析品牌分类 任务
     * @param insBrandMessages
     */
    @Override
    public void handleAnalysisBrandCategory(List<InsBrandMessage> insBrandMessages) {
        try {
            forkJoinPool.submit(() -> insBrandMessages.parallelStream().forEach(insBrandMessage -> {
                try {
                    // 分析品牌分类
                    analysisBrandCategory(insBrandMessage);
                } catch (Exception ex) {
                    log.error("insAnalysisBrandCategory error. bid:{}, error :{}" ,
                            insBrandMessage.getBid(),ex.getMessage());
                }
            })).get();
        } catch (Exception ex) {
            log.error("insAnalysisBrandCategory thread error.  {}" ,  ex.getMessage());
        }
    }

    /**
     * 分析品牌分类
     *
     * @param insBrandMessage
     */
    public void analysisBrandCategory(InsBrandMessage insBrandMessage){
        long start = System.currentTimeMillis();
        int bid = insBrandMessage.getBid();

        // 更新品牌分类
        insBrandDao.updateCategory(bid);

        if ((System.currentTimeMillis() - start) / 1000 > insAnalysisConfig.getInsAnalysisDebugTimeLimit()) {
            log.info("insAnalysisBrandCategory bid:{} use time:{}s", bid,(System.currentTimeMillis() - start) / 1000);
        }
    }
}
